#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <time.h>

typedef struct vector
{
    int size;
    int count;
    int *data;
} vector_t;

vector_t * get_new_vector(int size)
{
    vector_t *vector = (vector_t *)malloc(sizeof(vector_t));
    vector->size = size;
    vector->count = 0;
    vector->data = (int *)malloc(size);

    return vector;
}

int expand_vector(vector_t *v)
{
    if (v == NULL) return 0;
    printf("expand v from %d to %d\n", v->size, 2 * v->size);
    int *p = (int *)realloc(v->data, sizeof(int) * 2 * v->size);
    if (p == NULL) return 0;
    v->data = p;
    v->size *= 2;
    return 1;
}

int insert_vector(vector *v, int pos, int val)
{
    if (pos < 0 || pos > v->count) return 0;
	if (v->size == v->count && !expand_vector(v)) return 0;
    for (int i = v->count - 1; i >= pos; i--)
    {
        v->data[i + 1] = v->data[i];
    }
    v->data[pos] = val;
    v->count += 1;
    return 1;
}

int erase_vector(vector_t *v, int postion)
{
    if (postion < 0 || postion > v->size)
        return 0;
    if (v->count = 0)
        return 1;

    for (int i = postion -1; i < v->size; i++)
    {
        v->data[i + 1] = v->data[i];
    }

    v->count -= 1;
    return 1;  
}

void clear_vector(vector_t *v)
{
	if (v == NULL)
		return;
	free(v->data);
	free(v);
	return;
}

void output_vector(vector *v)
{
    int len = 0;
    for (int i = 0; i < v->size; i++)
    {
        len += printf("%3d", i);
    }
    printf("\n");
    for (int i = 0; i < len; i++) printf("-");
    printf("\n");
    for (int i = 0; i < v->count; i++)
    {
        printf("%3d", v->data[i]);
    }
    printf("\n");
    printf("\n\n");
    return ;
}


int main()
{	
    srand(time(0));
    #define MAX_OP 20
    vector_t *vector1 = get_new_vector(2);
    output_vector(vector1);

    for (int i = 0; i < MAX_OP; i++) {
        int op = rand() % 4, pos, val, ret;
        switch (op) {
            case 0:
            case 1:
            case 2:
                pos = rand() % (vector1->count + 2);
                val = rand() % 100;
                ret = insert_vector(vector1, pos, val);
                printf("insert %d at %d to vector = %d\n", 
                    val, pos, ret);
                break;
            case 3:
                pos = rand() % (vector1->count + 2);
                ret = erase_vector(vector1, pos);
                printf("erase item at %d in vector = %d\n", 
                    pos, ret);
                break;
        }
        output_vector(vector1);
    }
    clear_vector(vector1);
    return 0;
}
